/**
 * 修改一个路由参数的选择器事件（如每页条数pagesize）
 * 参数 num int 选择的参数值
 * 参数 name string 参数名称(选择器元素名称)
 */
function changeUrlParam(num, name) {
    var Params = new Array();
    //先获取参数数组
    Params = getUrlParams();
    //分析参数中是否存在当前元素名的参数
    if (Params[name] === undefined) {
        //不存在目标参数，则直接加上
        if (location.search) s = "&";
        else s = "?";
        location.href = location.href + s + encodeURI(name + "=" + num);
    } else {
        //存在目标参数，则修改后重新拼装
        Params[name] = num;
        s = toUrlParams(Params);
        location.href = location.pathname + '?' + encodeURI(s);
    }
}

/**
 *将路由中的参数转为数组
 */
function getUrlParams() {
    var url = decodeURI(location.search); //获取url中"?"符后的字串
    var theParams = new Array();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            param = strs[i].split("=");
            theParams[param[0]] = param[1];
        }
    }
    return theParams;
}

/**
 *将数组转成路由中的参数
 */
function toUrlParams(arr) {
    var theParams = new Array();
    k = 0;
    for (i in arr) {
        param = i + "=" + arr[i];
        theParams[k] = param;
        k++;
    }
    ;
    return theParams.join("&");
}

/**
 *边栏 比较商品 添加
 */
function contrastGoods(show, id, type) {
    if (show == 1) {
        //if(type==1)$("#j-cont-frame").removeClass('hidden');
        $.ajax({
            url: '/addons/mall/goods/contrastGoods',
            type: 'post',
            dataType: 'json',
            data: {id: id},
            success: function (ret) {
                if (ret.code) {
                    loadContrast();
                } else {
                    if (ret.msg) Toastr.error(ret.msg);
                }
            },
        });
    } else {
        $("#j-cont-frame").addClass('hidden');
    }
}

/**
 *删除
 */
function contrastDel(id) {
    $.ajax({
        url: '/addons/mall/goods/contrastDel',
        type: 'post',
        dataType: 'json',
        data: {id: id},
        success: function (ret) {
            if (ret.msg) Toastr.success(ret.msg);
            loadContrast();
        }
    });
}

/**
 *加载
 */
function loadContrast() {
    $.ajax({
        url: '/addons/mall/goods/loadContrastGoods',
        type: 'post',
        dataType: 'json',
        success: function (ret) {
            if (ret.code) {
                $('#compare-content').html(Template("colisttpl", ret.data));
                return false;
            } else {
                if (ret.msg) Toastr.error(ret.msg);
            }
        }
    });
}

/**
 *取消收藏
 */
cancelFavorite = function (obj, type, id, fId) {
    var str = '商品';
    str = (type == "shop") ? '店铺' : ((type == "goods") ? '商品' : ((type == "article") ? '文章' : ''));
    $.ajax({
        url: '/addons/mall/favorite/cancel',
        type: 'post',
        dataType: 'json',
        data: {id: fId, type: type,},
        success: function (ret) {
            if (ret.code) {
                if (ret.msg) Toastr.success(ret.msg);
                $(obj).find("i").removeClass('fa-heart').addClass('fa-heart-o');
                $(obj).find("span").text('收藏');
                $(obj).attr("title", '关注' + str).onclick = function () {
                    addFavorite(obj, type, id);
                };
                return false;
            } else {
                if (ret.msg) Toastr.error(ret.msg);
            }
        },
    });
}

/**
 *添加收藏
 */
addFavorite = function (obj, type, id) {
    $.ajax({
        url: '/addons/mall/favorite/add',
        type: 'post',
        dataType: 'json',
        data: {id: id, type: type,},
        success: function (ret) {
            if (ret.code) {
                if (ret.msg) Toastr.success(ret.msg);
                $(obj).find("i").removeClass('fa-heart-o').addClass('fa-heart');
                $(obj).find("span").text('已收藏');
                $(obj).attr("title", '已关注').onclick = function () {
                    cancelFavorite(obj, type, id, ret.data.fId);
                };
                return false;
            } else {
                if (ret.msg) Toastr.error(ret.msg);
            }
        },
    });
}

/**
 *添加商品到购物车
 */
function addCart(goods_id) {
    $.ajax({
        url: '/addons/mall/cart/add',
        type: 'post',
        dataType: 'json',
        data: {goods_id: goods_id, num: 1},
        success: function (ret) {
            if (ret.code) {
                if (ret.msg) Toastr.success(ret.msg);
                if(ret.data && ret.data.forward){
                    location.href='/addons/mall/cart/'+ret.data.forward;
                }
                getCartInfo();
            } else {
                if (ret.msg) Toastr.error(ret.msg);
            }
        },
    });
}

/**
 *刷新头部购物车
 */
function getCartInfo(goods_id) {
    if ($(".top-cart-contain").size() > 0) {
        $.ajax({
            url: '/addons/mall/cart/getCartInfo',
            success: function (ret) {
                var html = template("minicarttpl", ret);
                $(".top-cart-contain").html(html);
            },
        });
    }
}

/**
 *搜索按钮
 */
function btnSearch() {
    var sw = $.trim($('#searchword').val());
    if (sw == "") {
        Toastr.error("请输入搜索关键词！");
        return false;
    }
    if ($("#category_id").val() == "shop") {
        searchShop($.trim($('#searchword').val()));
    } else if ($("#category_id").val() == "goods") {
        searchGoods($.trim($('#searchword').val()));
    }
}

/**
 *搜店铺
 */
function searchShop(v) {
    location.href = '/addons/mall/shop/index/searchword/' + v;
}

/**
 *搜商品
 */
function searchGoods(v) {
    location.href = '/addons/mall/goods/index/searchword/' + v;
}

/**
 *搜店铺内商品
 */
function searchShopGoods() {
    $shop_id = $("#shop_id").val();
    $searchword = $("#searchword").val();
    location.href = '/addons/mall/goods/index?shop_id=' + $shop_id + "&searchword=" + $searchword;
}

/**
 *设置表单元素值(要求元素id和name值都为字段名加前缀c-)
 */
function setValue(name, value) {
    var first = name.substr(0, 3), input, i = 0, val;
    if ("#c-" === first || "." === first) {
        input = $(name);
    } else {
        input = $("[name='" + name + "']");
    }

    if (input.eq(0).is(":radio")) { //单选按钮
        input.filter("[value='" + value + "']").each(function () {
            this.checked = true
        });
    } else if (input.eq(0).is(":checkbox")) { //复选框
        if (!$.isArray(value)) {
            val = new Array();
            val[0] = value;
        } else {
            val = value;
        }
        for (i = 0, len = val.length; i < len; i++) {
            input.filter("[value='" + val[i] + "']").each(function () {
                this.checked = true
            });
        }
    } else {  //其他表单选项直接设置值
        input.val(value);
    }
}

/**
 *批量设置表单元素值(要求元素id和name值都为字段名加前缀c-)
 */
function setValues(obj) {
    var input, value, val;
    for (var key in obj) {
        if ($('#c-' + key)[0]) {
            setValue('#c-' + key, obj[key]);
        } else if ($("[name='" + key + "']")[0]) {
            setValue(key, obj[key]);
        }
    }
}

/**
 *获取表单元素值
 */
function getParams(obj) {
    var params = {};
    var chk = {}, s;
    $(obj).each(function () {
        if ($(this)[0].type == 'hidden' || $(this)[0].type == 'number' || $(this)[0].type == 'tel' || $(this)[0].type == 'password' || $(this)[0].type == 'select-one' || $(this)[0].type == 'textarea' || $(this)[0].type == 'text') {
            params[$(this).attr('id').substring(2)] = $.trim($(this).val());
        } else if ($(this)[0].type == 'radio') {
            if ($(this).attr('name')) {
                params[$(this).attr('name')] = $('input[name=' + $(this).attr('name') + ']:checked').val();
            }
        } else if ($(this)[0].type == 'checkbox') {
            if ($(this).attr('name') && !chk[$(this).attr('name')]) {
                s = [];
                chk[$(this).attr('name')] = 1;
                $('input[name=' + $(this).attr('name') + ']:checked').each(function () {
                    s.push($(this).val());
                });
                params[$(this).attr('name')] = s.join(',');
            }
        }
    });
    chk = null, s = null;
    return params;
}

function inEffect(obj,n){
    $(obj).addClass('j-selected').siblings('.mall-frame'+n).removeClass('j-selected');
}
/**
 *选择操作
 * @param int n 选项值
 * @param string index 字段名称
 * @param object obj 选项表单元素
 */
function changeSelected(n,index,obj){
    $('#c-'+index).val(n);
    inEffect(obj,2);
}

/**
 *表单元素关联隐显操作
 */
function showHide(t, str) {
    var s = str.split(',');
    if (t) {
        for (var i = 0; i < s.length; i++) {
            $(s[i]).show();
        }
    } else {
        for (var i = 0; i < s.length; i++) {
            $(s[i]).hide();
        }
    }
    s = null;
}

//发送私信
$(document).on("click", ".btn-message", function () {
    var that = this;

    layer.prompt({
        formType: 2,
        title: "发送私信",
        success: function (layero, index) {
            $("textarea", layero).prop("placeholder", "请输入私信内容");
        }
    }, function (value, index) {
        Fast.api.ajax({
            url: "message/post",
            data: {id: $(that).data("id"), content: value}
        }, function (data, ret) {
            layer.close(index);
        });
    });
});

//通知消息删除
$(document).on("click", ".belling ul li > em", function () {
    var that = this;
    Fast.api.ajax({
        url: $(that).prev().attr("href"),
        data: {act: "markall"}
    }, function (data, ret) {
        var ul = $(that).closest("ul");
        $(that).closest("li").remove();
        if ($("li", ul).size() === 0) {
            ul.prev().removeClass("unread");
            ul.remove();
        }
        return false;
    });

});

/**
 * 购物车减少商品数量
 * @param cart_id
 */
function decrease_num(cart_id){
    var item = $('#c-num_' + cart_id);
    var orig = Number(item.val());
    if(orig > 1){
        item.val(orig - 1);
        item.keyup();
    }else{
        layer.msg('购买数量不能小于1',{icon:2});
        return;
    }

}

/**
 * 购物车增加商品数量
 * @param cart_id
 */
function add_num(cart_id){
    var item = $('#c-num_' + cart_id);
    var orig = Number(item.val());
    var maxVal = Number(item.attr('data-max'),10);
    if(orig<maxVal){
        item.val(orig + 1);
        item.keyup();
    }else{
        layer.msg('购买数量不能超出库存数!',{icon:2});
        return;
    }

}

function imageFormatter(value, row, index) {
    var Config = requirejs.s.contexts._.config.config;
    value = value ? (Config.mallcdn ? Config.mallcdn : Config.upload.cdnurl) + value : '/assets/img/blank.gif';
    var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
    return '<a href="javascript:void(0)" target="_blank"><img class="' + classname + '" src="' + value + '" style="width:100px;heigh:100px"/></a>';
}

function goodsnameFormatter(value, row, index) {
    if(!row.goodstype && row.specis){
        return [
            value,
            '<p/>',
            row.goodsspecs.join(';<p/>'),
        ].join('');
    }else{
        return value;
    }
}

function numFormatter(value, row, index) {
    return [
        '<a href="JavaScript:void(0);" onclick="decrease_num(' + row.id + ');" title="减少数量" class="buy-btn">-</a>',
        '<input name="row[num]" id="c-num_' + row.id + '" value="' + value + '" orig="' + value + '" changed="' + value + '" onkeyup="change_num(' + row.id + ', this);" type="text" data-min="1" data-max="' + row.goodsstock + '" class="buy-num"/>',
        '<a href="JavaScript:void(0);" onclick="add_num(' + row.id + ');" title="增加数量" class="buy-btn" >+</a>'
    ].join('')
}

